package com.huixi.controller;

import com.huixi.Enums.JsonStatus;
import com.huixi.common.pojo.UserInfo;
import com.huixi.config.properties.JwtProperties;
import com.huixi.service.UserService;
import com.huixi.utils.CookieUtils;
import com.huixi.utils.JsonResult;
import com.huixi.utils.JwtUtils;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService userService;

	@Autowired
	private JwtProperties jwtProperties;

	/**
	 * 用户注册校验
	 * 
	 * @param verifyCode
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "/check/{verifyCode}/{type}")
	@ResponseBody
	public JsonResult check(@PathVariable("verifyCode") String verifyCode, @PathVariable("type") String type) {
		JsonResult jsonResult = new JsonResult();
		Boolean isExist = userService.existUser(verifyCode, type);
		if (BooleanUtils.isFalse(isExist)) {
			jsonResult.setStatus(JsonStatus.SUCCESS.getCode());
		}

		return jsonResult;
	}

	@RequestMapping("/token")
	@ResponseBody
	public JsonResult getUserByToken(HttpServletRequest request, HttpServletResponse response) {
		String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());
		UserInfo userInfo = null;
		try {
			if (StringUtils.isNotBlank(token)) {
				// 校验token令牌是否有效
				// 根据公钥，解析token，获取授权用户信息
				userInfo = JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
				// 解析成功重新刷新token（延续token的失效时间）
				String newToken = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(),
						jwtProperties.getExpire());
				// 更新cookie中的token
				CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), newToken,
						jwtProperties.getCookieMaxAge(), true);
				//request.setAttribute("userInfo", userInfo);
			}else {
				return JsonResult.build(400, "未登录");
			}
		} catch (Exception e) {
			return JsonResult.build(400, "获取用户信息失败");
		}
		return JsonResult.ok(userInfo);
	}
}
